﻿
Imports System.Threading
Imports osi.root.lock
Imports osi.root.connector
Imports osi.root.envs

Public Class qless2(Of T)
    Implements iqueue(Of T)

    Private ReadOnly q As slimqless2(Of T)
    Private _size As Int32

    Public Sub New()
        q = New slimqless2(Of T)()
        _size = 0
    End Sub

    Public Function empty() As Boolean Implements iqueue(Of T).empty
        Return size() = 0
    End Function

    Public Function size() As Int64 Implements iqueue(Of T).size
        '< 0 is in partial of pop operation
        Return If(_size < 0, 0, _size)
    End Function

    Public Sub clear() Implements islimqueue(Of T).clear
        q.clear()
    End Sub

    Public Function pop() As T Implements islimqueue(Of T).pop
        Dim o As T = Nothing
        If pop(o) Then
            Return o
        Else
            Return Nothing
        End If
    End Function

    Public Function pop(ByRef d As T) As Boolean Implements islimqueue(Of T).pop
        If Interlocked.Decrement(_size) >= 0 Then
            Return k_assert(q.pop(d))
        Else
            Interlocked.Increment(_size)
            Return False
        End If
    End Function

    Public Sub push(ByVal d As T) Implements islimqueue(Of T).push
        emplace_push(copy_no_error(d))
    End Sub

    Public Sub emplace_push(ByVal d As T) Implements islimqueue(Of T).emplace_push
        q.emplace_push(d)
        Interlocked.Increment(_size)
    End Sub

    'not a strict limitation
    Public Function push(ByVal d As T, ByVal max_size As Int64) As Boolean
        If size() >= max_size Then
            Return False
        Else
            push(d)
            Return True
        End If
    End Function
End Class
